var supplementEdit = {};
var SupplementEdit = function () {
    this.map = {};
    this.businessTypesMap = {};
    //存储存在的费用类型
    this.expenseExisting = {};
    //初始化
    this.init = function () {
        layui.use(['form'], function () {
            supplementEdit.form = layui.form;
        });
        layuiFunciton.layTime({
            elem: '#supplementaryDate'
        });
        //初始化数据字典
        if ($("#tranType").val() == "1") {//铁路运输
            //发出站
            supplementEdit.dictMap("aStation",  this.trim($("#aStation").text()));
            //到站
            supplementEdit.dictMap("arriveStation",this.trim($("#arriveStation").text()));
        } else if ($("#tranType").val() == "2") {//水路运输
            $("#goodsWere").text("提单号");
            $("#aStationText").text("发出港：");
            $("#arriveStationText").text("到港：");
            //发出港
            supplementEdit.dictMap("aStation", this.trim($("#aStation").text()));
            //到港
            supplementEdit.dictMap("arriveStation",  this.trim($("#arriveStation").text()));
        } else if ($("#tranType").val() == "3") {//公路运输
            //发出站
            supplementEdit.dictMap("aStation", this.trim($("#aStation").text()));
            //到站
            supplementEdit.dictMap("arriveStation",  this.trim($("#arriveStation").text()));
        }
        //业务类型
        supplementEdit.dictMap("businessTypes",this.trim($("#businessTypes").text()));
        //品名
        supplementEdit.dictMap("ofTheGoods",this.trim($("#ofTheGoods").text()));
        //箱型
        supplementEdit.dictMap("aBox", this.trim($("#aBox").text()));
        //发货单位
        supplementEdit.dictMap("deliveryUnit", this.trim($("#deliveryUnit").text()));
        //收货人
        //supplementEdit.dictMap("receivingUnit", this.trim($("#receivingUnit").text()));
        //结算人
        supplementEdit.dictMap("settlementPeople", this.trim($("#settlementPeople").text()));
        //议价号
        supplementEdit.dictMap("bargaining",  this.trim($("#bargaining").text()));
        //装货地点
        supplementEdit.dictMap("standby1",  this.trim($("#standby1").text()));

        supplementEdit.getDictType();
    };
    /**
     *  获取  费用类型，收款单位
     */
    this.getDictType = function () {
        //费用类型
        layuiFunciton.ajaxRequest({
            url: layuiFunciton.URL + '/sys/dictVal/getByTypeCode',
            method: 'get',
            maskState: false,
            async: false,   //是否为异步请求
            data: {
                typeCode: 'FYLX',
                enabled: 1
            },
            success: function (data) {
                supplementEdit.map['FYLX'] = data;
                //收款单位
                layuiFunciton.ajaxRequest({
                    url: layuiFunciton.URL + '/sys/dictVal/getByTypeCode',
                    method: 'get',
                    maskState: false,
                    async: false,   //是否为异步请求
                    data: {
                        typeCode: 'SKDW',
                        enabled: 1
                    },
                    success: function (data) {
                        supplementEdit.map['SKDW'] = data;
                        supplementEdit.findConditions();
                        supplementEdit.findSupplement();
                    }
                });
            }
        });
    };
    /**
     *
     * @param costType  费用类型
     * @param receivingUnit  收款单位
     * @param amountPayable  应付金额
     * @param realPayTotalAmount  实付金额
     * @param note   备注
     */
    this.addRow = function (costType, receivingUnit, amountPayable, realPayTotalAmount, note) {
        var rowHtml = `<tr>
                        <td>
                            ` + supplementEdit.joinSelect(costType) + `
                        </td>
                        <td>
                            ` + (amountPayable ? amountPayable : '') + `
                        </td>
                        <td>
                            ` + (realPayTotalAmount ? realPayTotalAmount : '') + `
                        </td>
                        <td>
                         ` + supplementEdit.joinSelect(receivingUnit) + `
                        </td>
                        <td>
                           ` + (note ? note : '') + `
                        </td>
                    </tr>`;
        $("#row").append(rowHtml);
        supplementEdit.form.render("select");
        layuiFunciton.moneyValidation(".money");
    };
    this.addNewRow = function (costType, receivingUnit, amountPayable, realPayTotalAmount, note) {
        var rowHtml = `<tr>
                        <td>
                            <select name="" class="">
                            ` + supplementEdit.newJoinSelect('FYLX', costType) + `
                           </select>
                        </td>
                        <td>
                            <div class="layui-table-cell"></div>
                            <input class="layui-input layui-table-edit money" value="` + (amountPayable ? amountPayable : '') + `" type="text"/>
                        </td>
                        <td>
                            <div class="layui-table-cell"></div>
                            <input class="layui-input layui-table-edit money"  value="` + (realPayTotalAmount ? realPayTotalAmount : '') + `" type="text"/>
                        </td>
                        <td>
                         <select name="" class=""  lay-search="">
                            ` + supplementEdit.newJoinSelect('SKDW', receivingUnit) + `
                           </select>
                        </td>
                        <td>
                            <div class="layui-table-cell"></div>
                            <input class="layui-input layui-table-edit" value="` + (note ? note : '') + `" type="text"/>
                        </td>
                        <td>
                            <div class="layui-table-cell"><a href="javascript:void(0)"
                                                             style="color:#009feb;padding-left: 8px;"
                                                             onclick="supplementEdit.delRow(this)">删除</a></div>
                        </td>
                    </tr>`;
        $("#newRow").append(rowHtml);
        supplementEdit.form.render("select");
        layuiFunciton.moneyValidation(".money");
    };
    //计算金额
    this.calculationAmount = function () {
        var totalCosts = 0.00;
        var totalCostsList = $(".totalCosts");
        for (var i = 0; i < totalCostsList.length; i++) {
            var value = totalCostsList.eq(i).val();
            totalCosts = (Number(totalCosts) + Number(value)).toFixed(2);
        }
        $("#totalCosts").val(totalCosts);
        $("#totalCostsHtml").html(totalCosts);
    };
    //删除一行
    this.delRow = function (obj) {
        $(obj).parents("tr").remove();
        supplementEdit.calculationAmount();
    };
    //拼接Select
    this.joinSelect = function (valCode) {
        var dictMap = layuiFunciton.sessionStorageGet("dictMap"); //数据字典
        if(valCode){
            if(dictMap[valCode]){
                return dictMap[valCode];
            }
        }
        return "";
    };
    //拼接Select
    this.newJoinSelect = function (code, defaultCode) {
        var optionHtml = '<option value="">请选择</option>';
        if(supplementEdit.map[code])
        supplementEdit.map[code].forEach(function (obj, index) {
            //if (!supplementEdit.expenseExisting[obj.valCode]) {
            if (obj.valCode == defaultCode) {
                optionHtml += '<option value="' + obj.valCode + '" selected>' + obj.valName + '</option>';
            } else {
                optionHtml += '<option value="' + obj.valCode + '">' + obj.valName + '</option>';
            }
            //}
        });
        return optionHtml;
    };
    //时间格式化
    this.dateFtt = function (fmt, date) {
        var o = {
            "M+": date.getMonth() + 1,     //月份
            "d+": date.getDate(),     //日
            "h+": date.getHours(),     //小时
            "m+": date.getMinutes(),     //分
            "s+": date.getSeconds(),     //秒
            "q+": Math.floor((date.getMonth() + 3) / 3), //季度
            "S": date.getMilliseconds()    //毫秒
        };
        if (/(y+)/.test(fmt))
            fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o)
            if (new RegExp("(" + k + ")").test(fmt))
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        return fmt;
    };
    //查询费用明细
    this.findConditions = function () {
        layuiFunciton.ajaxRequest({
            url: layuiFunciton.URL + '/wb/schedule/types/wbScheduleTypes',
            method: 'get',
            maskState: false,
            async: false,   //是否为异步请求
            data: {
                orderCode: $("#orderCode").val(),
                states: 0,
                reviewStatus: -1
            },
            success: function (data) {
                data.forEach(function (obj, index) {
                    supplementEdit.expenseExisting[obj.costType] = index;
                    supplementEdit.addRow(obj.costType, obj.receivingUnit, obj.amountPayable, obj.amountRealPay, obj.note);
                });
            }
        });
    };
    //查询增补费用明细
    this.findSupplement = function () {
        layuiFunciton.ajaxRequest({
            url: layuiFunciton.URL + '/wb/schedule/types/wbScheduleTypes',
            method: 'get',
            maskState: false,
            async: false,   //是否为异步请求
            data: {
                orderCode: $("#orderCode").val(),
                reviewStatus: 0,
                batchNumber: $("#batchNumber").val()
            },
            success: function (data) {
                data.forEach(function (obj, index) {
                    if (index == 0) {
                        $("#supplementarySpecification").val(obj.supplementarySpecification);
                    }
                    supplementEdit.addNewRow(obj.costType, obj.receivingUnit, obj.amountPayable, obj.amountRealPay, obj.note);
                });
            }
        });
    };
    this.trim = function (str) {
        return str.replace(/(^\s*)|(\s*$)/g, "");
    };
    this.event = function () {
        //保存
        layuiFunciton.filter({
            types: 'form',   //   注：仅支持 from 、table 两种类型  监听 table的 tools
            filterTypes: 'submit',   //
            filterName: 'submit',
            returnData: function (obj) {
                var formJSON = [];
                //获取费用类型
                var trs = $("#newRow").find("tr");
                var costTypeObj = {}, returnCostName, index = -1, tf = false;
                var copeWithTotalAmount = 0.00;//应付总金额
                var realPayTotalAmount = 0.00;//实付总金额
                var batchNumber = new Date().getTime();//批次号
                for (var k = 0; k < trs.length; k++) {
                    var tds = trs.eq(k).find("td");
                    //费用类型 字典值
                    var costType = tds.eq(0).find("select").val();
                    var costName = tds.eq(0).find("select").find("option:selected").text();
                    //应付金额
                    var amountPayable = tds.eq(1).find("input").val();
                    copeWithTotalAmount = (Number(copeWithTotalAmount) + Number(amountPayable ? amountPayable : 0.00)).toFixed(2);
                    //实付金额
                    var amountRealPay = tds.eq(2).find("input").val();
                    realPayTotalAmount = (Number(realPayTotalAmount) + Number(amountRealPay ? amountRealPay : 0.00)).toFixed(2);
                    //收款单位 字典值
                    var receivingUnit = tds.eq(3).find("select").val();
                    //备注
                    var note = tds.eq(4).find("input").val();

                    //验证
                    if (costTypeObj[costType]) {
                        if (costTypeObj[costType] == receivingUnit) {
                            index = k;
                            returnCostName = costName;
                        }
                    } else {
                        if (costType) {
                            costTypeObj[costType] = receivingUnit;
                        } else {
                            tf = true;
                        }
                    }
                    formJSON.push({
                        costType: costType,
                        amountPayable: amountPayable,
                        amountRealPay: amountRealPay,
                        receivingUnit: receivingUnit,
                        note: note,
                        states: 1,
                        batchNumber: $("#batchNumber").val(),
                        orderCode: $("#orderCode").val(),
                        reviewStatus: 0,
                        supplementaryDate: $("#supplementaryDate").val(),
                        supplementarySpecification: $("#supplementarySpecification").val(),
                        creationTime: supplementEdit.dateFtt('yyyy-MM-dd hh:mm:ss', new Date())
                    });
                }
                if (trs.length == 0) {
                    layuiFunciton.warn('费用明细不能为空！');
                    return;
                }
                if (copeWithTotalAmount == 0.00) {
                    layuiFunciton.warn('应收金额不能为空！');
                    return;
                }
                if (tf) {
                    layuiFunciton.warn('费用类型不能为空！');
                    return;
                }
                if (index > -1) {
                    layuiFunciton.warn('费用类型“' + returnCostName + '”重复！');
                    return;
                }
                //请求后台
                layuiFunciton.ajaxRequest({
                    url: layuiFunciton.URL + '/wb/schedule/types/supplement',
                    method: 'post',
                    contentType: "application/json; charset=utf-8",
                    data: JSON.stringify(formJSON),
                    success: function (data) {
                        if (data > 0) {
                            layuiFunciton.success("操作成功！", function () {
                                layuiFunciton.closeOpen();
                            })
                        } else {
                            layuiFunciton.warn('操作失败！');
                        }
                    }, error: function () {
                        layuiFunciton.closeOpen();
                    }
                });
            }
        });
    }
    this.dictMap = function (item,valCode) {
        var dictMap = layuiFunciton.sessionStorageGet("dictMap"); //数据字典
        if(dictMap[valCode]){
            $("#"+item).text(dictMap[valCode]);
        }else{
            $("#"+item).text("");
        }
    }
};
function pageReady() {
    supplementEdit = new SupplementEdit();
    supplementEdit.init();
    supplementEdit.event();
}